package com.lg.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lg.product.entity.Category;
import com.lg.product.mapper.CategoryMapper;
import com.lg.product.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 商品类目表，类目和商品(spu)是一对多关系，类目与品牌是多对多关系 服务实现类
 * </p>
 *
 * @author zhanggm
 * @since 2020-07-22
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    /**
     * 根据parentId查询分类以及子分类，递归查询
     * @param parentId
     * @return
     */
    @Override
    public List<Category> getCategoryTree(Long parentId) {
        //查询所有分类数据
        List<Category> categoryAll = getCategoryAll();
        //根据parentId查询分类列表
        List<Category> categoryList = getCategoryList(categoryAll,parentId);
        //遍历一级分类，查找子分类
        categoryList.forEach(category -> {
            getSubCate(category,categoryAll);
        });
        //返回结果
        return categoryList;
    }

    /**
     * 递归查询分类方法
     * @param category
     */
    public void getSubCate(Category category,List<Category> categoryAll){
        //根据当前分类的id，查询子分类
        List<Category> categoryList = getCategoryList(categoryAll,category.getId());
        if(categoryList.size()>0){
            //设置子分类
            category.setSubCateList(categoryList);
            //查询子分类是否有下级分类
            categoryList.forEach(subCate -> {
                getSubCate(subCate,categoryAll);
            });
        }
    }

    /**
     * 根据parentId查询分类列表
     * @param parentId
     * @return
     */
    public List<Category> getCategoryList(Long parentId) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("parent_id",parentId);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 从cateList查找parentId等于parentId
     * @param cateList
     * @param parentId
     * @return
     */
    public List<Category> getCategoryList(List<Category> cateList,Long parentId) {
        List<Category> list = new ArrayList<>();
        cateList.forEach(category -> {
            if(category.getParentId().intValue()==parentId.intValue()){
                list.add(category);
            }
        });
        return list;
    }

    /**
     * 查询所有分类数据
     * @return
     */
    public List<Category> getCategoryAll() {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByAsc("sort");
        return this.baseMapper.selectList(queryWrapper);
    }

}
